import React, { useEffect, useState } from 'react';
import { motion, AnimatePresence, useAnimation } from 'framer-motion';
import { Clock } from 'lucide-react'; 

// 动画计数器组件
const AnimatedCounter = ({ value, className = "" }) => (
  <motion.span
    key={value}
    initial={{ scale: 1.2, opacity: 0 }}
    animate={{ scale: 1, opacity: 1 }}
    exit={{ scale: 0.8, opacity: 0 }}
    transition={{ duration: 0.4, ease: "easeOut" }}
    className={className}
  >
    {value}
  </motion.span>
);

// 积分叠加动画组件
const PointsIncrement = ({ points, onComplete }) => {
  const [isVisible, setIsVisible] = useState(true);

  useEffect(() => {
    const timer = setTimeout(() => {
      setIsVisible(false);
      onComplete();
    }, 1000);

    return () => clearTimeout(timer);
  }, [onComplete]);

  return (
    <AnimatePresence>
      {isVisible && (
        <motion.div
          initial={{ y: 0, opacity: 1, scale: 1 }}
          animate={{ y: -40, opacity: 0, scale: 1.3 }}
          exit={{ opacity: 0 }}
          transition={{ duration: 1, ease: "easeOut" }}
          style={{
            position: 'absolute',
            color: '#4ade80',
            fontWeight: 'bold',
            fontSize: '1.25rem',
            pointerEvents: 'none',
            zIndex: 10
          }}
        >
          +{points}
        </motion.div>
      )}
    </AnimatePresence>
  );
};

const PointsCircle = ({
  totalPoints,
  sessionPoints,
  onCycleComplete,
  isTimerActive,
  canEarnPoints,
  nextAvailability,
}) => {
  const controls = useAnimation();
  const cycleDuration = 8; // 8秒一个周期
  const [incrementPoints, setIncrementPoints] = useState(0);
  const [showIncrement, setShowIncrement] = useState(false);

  // 计算半径为8的圆圈的周长
  const radius = 8;
  const circumference = 2 * Math.PI * radius; // 约等于 50.27

  // 顺时针流水动画控制
  useEffect(() => {
    if (isTimerActive && canEarnPoints) {
      controls.start({
        strokeDashoffset: 0,
        transition: {
          duration: cycleDuration,
          ease: "linear",
          repeat: Infinity,
        },
      });
    } else {
      controls.stop();
      controls.set({ strokeDashoffset: circumference });
    }
  }, [isTimerActive, canEarnPoints, controls, cycleDuration, circumference]);

  // 积分累积定时器
  useEffect(() => {
    let intervalId;
    if (isTimerActive && canEarnPoints) {
      intervalId = setInterval(() => {
        const randomPoints = Math.floor(Math.random() * (30 - 11 + 1)) + 11;
        setIncrementPoints(randomPoints);
        setShowIncrement(true);
        onCycleComplete();
      }, cycleDuration * 1000);
    }
    return () => clearInterval(intervalId);
  }, [isTimerActive, canEarnPoints, onCycleComplete, cycleDuration]);

  const handleIncrementComplete = () => {
    setShowIncrement(false);
  };

  if (!canEarnPoints) {
    return (
      <div
        className="absolute flex items-center gap-[0.2rem] px-[0.4rem] py-[0.2rem] text-[0.24rem] font-medium text-orange-500 bg-gradient-to-r from-orange-100/70 via-yellow-100/60 to-orange-50/60 border border-orange-300 rounded-full shadow-lg backdrop-blur-md animate-pulse"
        style={{
          position: 'absolute',
          width: '2rem',
          top: '0.5rem',
          left: '2.1rem',
          zIndex: 20,
          fontSize: '0.3rem',
          color: '#FF9933',
        }}
      >
        <Clock size={26} className="text-orange-400" />
        <span className="drop-shadow-sm">
          {nextAvailability}  <br />
          后可获积分
        </span>
      </div>
    );
  }
  return (
    <div className="flex flex-col items-center text-white relative" style={{ zIndex: 9999 }}>
      {/* 圆圈容器 - 调整为更小的尺寸适配半径为8的圆圈 */}
      <div className="relative w-[3.2rem] h-[3.2rem] flex items-center justify-center">
        {/* 总积分显示 - 固定在圆圈正上方 */}
          <div style={{
          position: 'absolute',
          top: '0.4rem',
          left: '3.26rem',
          transform: 'translateX(-55%)',
          alignItems: 'center',
          zIndex: 10
        }}>
           {/* <div style={{ fontSize: '0.35rem', fontWeight: 600, color: 'rgb(145, 124, 9)', marginBottom: '0.325rem' }}>总积分</div> */}
<div style={{ 
  fontSize: '0.4rem',
  fontWeight: 600,
  background: 'linear-gradient(to right, rgb(192, 132, 252), rgb(236, 72, 153), rgb(239, 68, 68))',
  color: 'transparent',
  backgroundClip: 'text',
  WebkitBackgroundClip: 'text',
  padding: '0.1rem 1rem',
  borderRadius: '0.75rem',
  boxShadow: '0 25px 50px -12px rgba(0, 0, 0, 0.25)',
  // border: '1px solid rgba(255, 255, 255, 0.3)',
  filter: 'drop-shadow(0 4px 3px rgba(0, 0, 0, 0.07))'
}}> 
  <AnimatePresence mode="wait">
    <AnimatedCounter value={totalPoints} />
  </AnimatePresence>
</div>

   {/* 圈内积分数字 - 调整为更小的字体适配小圆圈 */}
   <div style={{
          position: 'absolute',
          top: '1.1rem',
          left: '0.32rem',
          right: 0,
          bottom: 0,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          color: '#FF9933',
          fontSize: '0.2rem',
          zIndex: 10
        }}>
          <div className="text-[0.48rem]">
            <AnimatePresence mode="wait">
              <AnimatedCounter value={sessionPoints} />
            </AnimatePresence>
          </div>
        </div>
        </div>

        {/* 背景圆圈 */}
        <svg
            className="absolute"
            style={{
              width: '3.5rem',
              height: '3rem',
              top: '0.01rem',
              left: '1.5rem',
              position: 'absolute',
            }}
            viewBox="0 0 100 100"
            preserveAspectRatio="xMidYMid meet"
          >
          {/* 外层背景圆圈 */}
          <circle
            cx="50"
            cy="50"
            r={radius}
            stroke="#ffffff20"
            strokeWidth="4"
            fill="transparent"
            strokeLinecap="round"
          />
          
          {/* 中层圆圈 */}
          <circle
            cx="50"
            cy="50"
            r={radius}
            stroke="#9AB0EC"
            strokeWidth="3"
            fill="transparent"
            strokeLinecap="round"
          /> 
          
          {/* 动画进度圆圈 */}
          <motion.circle
            cx="50"
            cy="50"
            r={radius}
            stroke="#4ade80"
            strokeWidth="3"
            fill="transparent"
            strokeLinecap="round"
            strokeDasharray={circumference}
            strokeDashoffset={circumference}
            initial={{ strokeDashoffset: circumference }}
            animate={controls}
            style={{
              transformOrigin: "50% 50%",
              transform: "rotate(-90deg)",
            }}
          />
        </svg>

     

        {/* 积分叠加动画 */}
        {showIncrement && (
          <PointsIncrement
            points={incrementPoints}
            onComplete={handleIncrementComplete}
          />
        )}
      </div>
    </div>
  );
};

export default PointsCircle;
